<template>
  <div class="outing-apply-container">
    <div class="page-header">
      <h1>外出申请</h1>
      <p>为自家老人申请外出活动</p>
    </div>

    <div class="content-wrapper">
      <!-- 申请表单 -->
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>外出申请信息</span>
          </div>
        </template>
        
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          :disabled="loading"
        >
          <el-form-item label="选择老人" prop="elderId">
            <el-select
              v-model="form.elderId"
              placeholder="请选择要外出的老人"
              style="width: 100%"
              @change="handleElderChange"
            >
              <el-option
                v-for="elder in myElders"
                :key="elder.elderId"
                :label="`${elder.name} (${elder.bedNumber})`"
                :value="elder.elderId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="外出目的" prop="outingReason">
            <el-input
              v-model="form.outingReason"
              type="textarea"
              :rows="3"
              placeholder="请详细说明外出目的，如：家庭聚餐、医院复查、公园散步等"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="目的地" prop="destination">
            <el-input
              v-model="form.destination"
              placeholder="请输入具体目的地"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="外出时间" required>
            <el-col :span="11">
              <el-form-item prop="startTime">
                <el-date-picker
                  v-model="form.startTime"
                  type="datetime"
                  placeholder="选择开始时间"
                  style="width: 100%"
                  :disabled-date="disabledStartDate"
                />
              </el-form-item>
            </el-col>
            <el-col :span="2" class="text-center">-</el-col>
            <el-col :span="11">
              <el-form-item prop="endTime">
                <el-date-picker
                  v-model="form.endTime"
                  type="datetime"
                  placeholder="选择结束时间"
                  style="width: 100%"
                  :disabled-date="disabledEndDate"
                />
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item label="预计返回时间" prop="estimatedReturnTime">
            <el-date-picker
              v-model="form.estimatedReturnTime"
              type="datetime"
              placeholder="选择预计返回时间"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="同行人员" prop="companionInfo">
            <el-input
              v-model="form.companionInfo"
              type="textarea"
              :rows="2"
              placeholder="请填写同行人员信息，如：儿子张三、女儿李四等"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="详细说明" prop="purpose">
            <el-input
              v-model="form.purpose"
              type="textarea"
              :rows="4"
              placeholder="请详细说明外出活动的具体安排和注意事项"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm" :loading="loading">
              提交申请
            </el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 老人信息卡片 -->
      <el-card class="info-card" v-if="selectedElder">
        <template #header>
          <div class="card-header">
            <span>老人信息</span>
          </div>
        </template>
        <div class="elder-info">
          <div class="info-row">
            <label>姓名：</label>
            <span>{{ selectedElder.name }}</span>
          </div>
          <div class="info-row">
            <label>年龄：</label>
            <span>{{ selectedElder.age }}岁</span>
          </div>
          <div class="info-row">
            <label>性别：</label>
            <span>{{ selectedElder.gender === 1 ? '男' : '女' }}</span>
          </div>
          <div class="info-row">
            <label>床位：</label>
            <span>{{ selectedElder.bedNumber }}</span>
          </div>
          <div class="info-row">
            <label>健康状况：</label>
            <span>{{ selectedElder.healthStatus }}</span>
          </div>
          <div class="info-row">
            <label>负责护工：</label>
            <span>{{ selectedElder.caregiverName || '--' }}</span>
          </div>
          <div class="info-row">
            <label>护工电话：</label>
            <span>{{ selectedElder.caregiverPhone || '--' }}</span>
          </div>
        </div>
      </el-card>

      <!-- 申请记录 -->
      <el-card class="records-card">
        <template #header>
          <div class="card-header">
            <span>我的申请记录</span>
            <el-button type="text" @click="refreshRecords">刷新</el-button>
          </div>
        </template>
        
        <el-table
          :data="applyRecords"
          v-loading="recordsLoading"
          style="width: 100%"
        >
          <el-table-column prop="elderName" label="老人" width="100" />
          <el-table-column prop="outingReason" label="外出目的" min-width="120" />
          <el-table-column prop="destination" label="目的地" width="120" />
          <el-table-column label="外出时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.startTime) }}<br/>
              至 {{ formatDateTime(row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="applyStatus" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.applyStatus)">
                {{ getStatusText(row.applyStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button
                v-if="row.applyStatus === 0"
                type="text"
                size="small"
                @click="cancelApply(row.applyId)"
              >
                取消
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="viewDetail(row.applyId)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const formRef = ref()
const loading = ref(false)
const recordsLoading = ref(false)

const form = reactive({
  elderId: '',
  outingReason: '',
  destination: '',
  startTime: '',
  endTime: '',
  estimatedReturnTime: '',
  companionInfo: '',
  purpose: ''
})

const rules = {
  elderId: [
    { required: true, message: '请选择要外出的老人', trigger: 'change' }
  ],
  outingReason: [
    { required: true, message: '请输入外出目的', trigger: 'blur' },
    { min: 5, message: '外出目的至少5个字符', trigger: 'blur' }
  ],
  destination: [
    { required: true, message: '请输入目的地', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  estimatedReturnTime: [
    { required: true, message: '请选择预计返回时间', trigger: 'change' }
  ]
}

// 模拟数据
const myElders = ref([
  {
    elderId: 1,
    name: '张大爷',
    age: 78,
    gender: 1,
    bedNumber: '101-A',
    healthStatus: '高血压、糖尿病',
    caregiverName: '张护工',
    caregiverPhone: '13800138000'
  },
  {
    elderId: 2,
    name: '李大妈',
    age: 82,
    gender: 0,
    bedNumber: '102-A',
    healthStatus: '关节炎、骨质疏松',
    caregiverName: '李护工',
    caregiverPhone: '13800138001'
  }
])

const selectedElder = ref(null)

const applyRecords = ref([
  {
    applyId: 1,
    elderName: '张大爷',
    outingReason: '家庭聚餐',
    destination: '家中',
    startTime: '2024-10-05 10:00:00',
    endTime: '2024-10-05 18:00:00',
    applyStatus: 1 // 1-已批准, 0-待审批, 2-已拒绝
  },
  {
    applyId: 2,
    elderName: '李大妈',
    outingReason: '医院复查',
    destination: '人民医院',
    startTime: '2024-10-06 09:00:00',
    endTime: '2024-10-06 12:00:00',
    applyStatus: 0
  }
])

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(2)

onMounted(() => {
  loadApplyRecords()
})

const loadApplyRecords = () => {
  recordsLoading.value = true
  // 模拟API调用
  setTimeout(() => {
    recordsLoading.value = false
  }, 500)
}

const handleElderChange = (elderId) => {
  selectedElder.value = myElders.value.find(elder => elder.elderId === elderId) || null
}

const disabledStartDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 不能选择今天之前的时间
}

const disabledEndDate = (time) => {
  if (!form.startTime) return time.getTime() < Date.now() - 8.64e7
  return time.getTime() <= form.startTime.getTime()
}

const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true
    
    // 模拟API调用
    setTimeout(() => {
      ElMessage.success('外出申请提交成功，请等待审批')
      resetForm()
      loadApplyRecords()
      loading.value = false
    }, 1000)
  } catch (error) {
    ElMessage.error('请完善表单信息')
  }
}

const resetForm = () => {
  formRef.value?.resetFields()
  selectedElder.value = null
}

const refreshRecords = () => {
  loadApplyRecords()
  ElMessage.success('已刷新申请记录')
}

const cancelApply = async (applyId) => {
  try {
    await ElMessageBox.confirm('确定要取消这条外出申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟取消申请
    ElMessage.success('申请已取消')
    loadApplyRecords()
  } catch (error) {
    // 用户取消操作
  }
}

const viewDetail = (applyId) => {
  ElMessage.info(`查看申请详情 ID: ${applyId}`)
  // 实际项目中这里应该跳转到详情页面或显示详情弹窗
}

const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getStatusText = (status) => {
  const statusMap = {
    0: '待审批',
    1: '已批准',
    2: '已拒绝'
  }
  return statusMap[status] || '未知'
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || 'info'
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  loadApplyRecords()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadApplyRecords()
}
</script>

<style scoped>
.outing-apply-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;
  text-align: center;
}

.page-header h1 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 28px;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 16px;
}

.content-wrapper {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.form-card {
  grid-column: 1;
}

.info-card {
  grid-column: 2;
}

.records-card {
  grid-column: 1 / span 2;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #303133;
}

.text-center {
  text-align: center;
  line-height: 40px;
}

.elder-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-row {
  display: flex;
  align-items: center;
}

.info-row label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
  margin-right: 10px;
}

.info-row span {
  color: #303133;
  flex: 1;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .content-wrapper {
    grid-template-columns: 1fr;
  }
  
  .form-card,
  .info-card,
  .records-card {
    grid-column: 1;
  }
}

@media (max-width: 768px) {
  .outing-apply-container {
    padding: 10px;
  }
  
  .page-header h1 {
    font-size: 24px;
  }
  
  .page-header p {
    font-size: 14px;
  }
  
  .content-wrapper {
    gap: 15px;
  }
}
</style>
